package top.drinyeit.nongmao.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import top.drinyeit.nongmao.R;
import top.drinyeit.nongmao.app.Constant;
import top.drinyeit.nongmao.base.BaseActivity;
import top.drinyeit.nongmao.dialog.AddCartDialog;
import top.drinyeit.nongmao.presenter.CommodityDetailNewPresenter;
import top.drinyeit.nongmao.retrofit.HttpResponse;
import top.drinyeit.nongmao.retrofit.RetrofitMethod;
import top.drinyeit.nongmao.retrofit.subscriber.CommonSubscriber;
import top.drinyeit.nongmao.retrofit.subscriber.SubscriberListener;
import top.drinyeit.nongmao.util.DensityUtil;
import top.drinyeit.nongmao.util.SPUtil;
import top.drinyeit.nongmao.view.CarouselView;

import static top.drinyeit.nongmao.app.Constant.COMMON_SUCCESS;

/**
 * Created by wu on 2018/1/10.
 */

public class CommodityDetailNewActivity extends BaseActivity {

    public static final String TAG = "CommodityActivity";
    public NestedScrollView nestedScrollView;
    public CarouselView mCarouselView;
    public RecyclerView mRecyclerView;
    public ImageView  back,back1;
    private TextView back0;
    public TextView price, commodity_name, store_name,stockNumberText;
    private ImageView cart;
    private AppBarLayout appBarLayout;
    private Toolbar toolbar;
    private TextView buy,tit;
    public int stockNumber;
    public double saldPrice;
    private int num = 1;

    private int id;

    public int resultCode = 0;

    private CommodityDetailNewPresenter commodityDetailNewPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_detail_new);

        initIntent();
        initView();
        initData();
        initListener();
        setToolbar();
    }

    private void initIntent(){
        Bundle bundle = getIntent().getExtras();
        id = bundle.getInt("id");
    }

    private void initView() {
        tit = findViewById(R.id.tv_tit);
        appBarLayout = findViewById(R.id.mAppBarLayout);
        toolbar = findViewById(R.id.AppFragment_Toolbar);
        mCarouselView = findViewById(R.id.mCarouselView);
        back0 = findViewById(R.id.back0);
        back = findViewById(R.id.back);
        back1 = findViewById(R.id.back1);
        mRecyclerView = findViewById(R.id.mRecyclerView);
        price = findViewById(R.id.price);
        store_name = findViewById(R.id.store_name);
        commodity_name = findViewById(R.id.commodity_name);
        cart = findViewById(R.id.cart);
        buy = findViewById(R.id.buy);
        nestedScrollView = findViewById(R.id.nsv_scroll);
        stockNumberText = findViewById(R.id.tv_stock_number);

        setTitle();
    }

    private void setToolbar(){
        int statusBarHeight1 = -1;//状态栏高度
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelOffset(resourceId);
        }

        CollapsingToolbarLayout.LayoutParams frameParams = (CollapsingToolbarLayout.LayoutParams) toolbar.getLayoutParams();
        frameParams.height = statusBarHeight1 + DensityUtil.dip2px(this,44);

        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                Log.e(TAG,"range:" + appBarLayout.getTotalScrollRange() + "      height:" + appBarLayout.getHeight() + "   verticalOffset:" + verticalOffset);
                back.setImageAlpha((int) (255 - Math.abs(verticalOffset*1.0f)/appBarLayout.getTotalScrollRange()*255));
                back1.setImageAlpha((int)  Math.abs(verticalOffset*1.0f)/appBarLayout.getTotalScrollRange()*255);
                toolbar.setBackgroundColor(changeAlpha(getResources().getColor(R.color.transparent),Math.abs(verticalOffset*0.9f)/appBarLayout.getTotalScrollRange() ));
                tit.setTextColor(changeAlpha(getResources().getColor(R.color.black),Math.abs(verticalOffset*1.0f)/appBarLayout.getTotalScrollRange()));

            }
        });
    }

    private void initData(){
        commodityDetailNewPresenter = new CommodityDetailNewPresenter(this);
        Map<String,Object> map = new HashMap<>();
        map.put("action","commodity_detail");
        map.put("commodity_id",id);
        commodityDetailNewPresenter.getCommodityDetail(map);
    }
    private void initListener(){
        back0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        back1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDialog();
            }
        });
        cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CommodityDetailNewActivity.this,MainActivity.class);
                intent.putExtra("position",2);
                startActivity(intent);
            }
        });
    }

    private void getDialog(){
        final AddCartDialog addCartDialog = new AddCartDialog(CommodityDetailNewActivity.this,R.layout.dialog_add_cart);
        addCartDialog.show();
        final TextView commodity_name,sale_price,add_cart,number;
        final RelativeLayout subtract,add;
        commodity_name = addCartDialog.findViewById(R.id.commodity_name);
        sale_price = addCartDialog.findViewById(R.id.sale_price);
        add_cart = addCartDialog.findViewById(R.id.add_cart);
        number = addCartDialog.findViewById(R.id.number);
        subtract = addCartDialog.findViewById(R.id.subtract);
        add = addCartDialog.findViewById(R.id.add);
        commodity_name.setText(this.commodity_name.getText());
        sale_price.setText(this.price.getText());
        if (stockNumber > 1){
            add.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.click_border));
        }
        subtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num--;
                changeNumber();
                number.setText(num + "");
                sale_price.setText("¥" + totalMoney(num * saldPrice) + "");
                if (num > 1){
                    subtract.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.click_border));
                }else {
                    subtract.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.unclick_border));
                }
                if (num < stockNumber){
                    add.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.click_border));
                }else {
                    add.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.unclick_border));
                }
            }
        });
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num ++;
                changeNumber();
                number.setText(num + "");
                sale_price.setText("¥" + totalMoney(num * saldPrice) + "");
                if (num < stockNumber){
                    add.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.click_border));
                }else {
                    add.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.unclick_border));
                }
                if (num > 1){
                    subtract.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.click_border));
                }else {
                    subtract.setBackground(ContextCompat.getDrawable(CommodityDetailNewActivity.this,R.drawable.unclick_border));
                }
            }
        });
        add_cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resultCode = 0;
                Map<String,Object> map = new HashMap<>();
                String user_id = SPUtil.getShareString(Constant.USER_ID);
                map.put("action","commodity_add_shopping_cart");
                map.put("user_id",user_id);
                map.put("commodity_id",id);
                map.put("commodity_sum",num);
                showLoading();
                CommonSubscriber<HttpResponse<String>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<String>>() {
                    @Override
                    public void onError(String e, int code) {
                        dismissLoading();
                        showToastMsg(e);
                    }

                    @Override
                    public void onNext(HttpResponse<String> o) {
                        dismissLoading();
                        if (o.getCode() == COMMON_SUCCESS){
                            showToast(o.getMessage());
                            resultCode = 1;
                            addCartDialog.dismiss();
                        }else {
                            showToast(o.getMessage());
                        }
                    }
                });
                RetrofitMethod.getInstance().addCart(subscriber,map);
            }
        });
    }

    private void changeNumber(){
        if (num > stockNumber){
            num = stockNumber;
            showToast("库存不足");
        }else if (num < 1){
            num = 1;
        }
    }

    public static String totalMoney(double money) {
        BigDecimal bigDec = new BigDecimal(money);
        double total = bigDec.setScale(2, BigDecimal.ROUND_HALF_UP)
                .doubleValue();
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(total);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        setResult(resultCode);
        finish();
        return super.onKeyDown(keyCode, event);

    }

    /** 根据百分比改变颜色透明度 */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

}
